package com.zxl.controller;

import com.zxl.constants.RedisConstants;
import com.zxl.feign.UserFeign;
import com.zxl.vo.Customer;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.scope.AuthBaiduScope;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

/**
 * @packageName com.zxl.controller
 * @ClassName
 * @Author zxl
 * @Description //TODO
 * @date
 **/
@Controller
@RequestMapping("/justauth")
public class JustAuthController {

    @Autowired
    private UserFeign userFeign;

    @RequestMapping("/auth")
    public void toAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        String authorize = authRequest.authorize(AuthStateUtils.createState());
        response.sendRedirect(authorize);
    }

    @RequestMapping("/callback")
    public String callback(AuthCallback authCallback, HttpSession httpSession) {
        String code = authCallback.getCode();
        System.out.println("code====>" + code);
        AuthRequest authRequest = getAuthRequest();
        AuthResponse login = authRequest.login(authCallback);

        if (login.ok()) {
            AuthUser data = (AuthUser) login.getData();
            AuthToken token = data.getToken();

            System.out.println("data==========>" + data);
            String username = data.getUsername();
            String uuid = data.getUuid();
            Customer customer = userFeign.findByoauthId(uuid);
            if (customer == null) {
                customer = new Customer();
                customer.setUsername(username);
                customer.setOauthId(uuid);
                customer = userFeign.reg(customer);
            }
            httpSession.setAttribute(RedisConstants.USER_LOGIN_SESSION_KEY, customer);
            return "redirect:http://localhost/home/home/";
        } else {
            return "redirect:http://localhost/auth/user/login.html";
        }
    }

    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("P6oB5Vp5ZITNXO4DC0fC55B3")
                .clientSecret("NMoyqIArLRGb2caUeVZ2wMs2BhtGClhk")
                .redirectUri("http://localhost/auth/justauth/callback")
                .scopes(Arrays.asList(AuthBaiduScope.SUPER_MSG.getScope()))
                .build());
    }
}
